package com.lcx.bean;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class StageClosingLisenerBean {

    private Map<String,OnCloseRequest> closeRequestMap = new HashMap<>(5);

    public List<OnCloseRequest> getAll(){
        if(closeRequestMap.isEmpty()) return null;
        return closeRequestMap.values().stream().collect(Collectors.toList());
    }

    public void add(String key,OnCloseRequest onCloseRequest){
        if(key == null) throw new RuntimeException("key不能为空！");
        if(closeRequestMap.get(key)!=null) throw new RuntimeException("key已存在！");
        closeRequestMap.put(key,onCloseRequest);
    }

    public void remove(String key){
        closeRequestMap.remove(key);
    }

    public void clear(){
        closeRequestMap.clear();
    }

    public synchronized void removeStartWith(String key){
        if(closeRequestMap.isEmpty()) return;
        List<String> keys = closeRequestMap.keySet().stream().filter(k->k.startsWith(key)).collect(Collectors.toList());
        if(keys.isEmpty()) return;
        keys.stream().forEach(closeRequestMap::remove);
    }

    public interface OnCloseRequest{
        void closing();
    }

}
